<?php

include_once("core/controller.php");
include_once("core/versionHandler.php");
include_once("models/maps/map.php");

/**
 * @copyright joel SIMOes
 * @package map
 *
 */
class mapEditor extends Controller{
	private $map_id;
	private $currentMap;
	private $doorPoints = array();


	public function isLegitimate(){



		$this->map_id = round($this->request->get("id"));
		$this->currentMap = new Map("rw", "id", $this->map_id);
		if (!$this->currentMap->isOk())
		{
			return false;
		}

		return true;
	}

	public function actions(){



		$versionH = new VersionHandler("");
		$this->response->add($versionH->getMyVersion());

		/**
		 $this->map_id = round($this->request->get("id"));

		 $this->currentMap = new Map("rw", "id", $this->map_id);
		 */

		if (!$this->currentMap->isOk())
		{
			$this->response->addError("This map does not exist","id");
		}else{
			if ($this->request->get("actionmod") == "mapDoorsList")
			{
				$this->getMapsDoors();
				return;
			}

			if ($this->request->get("actionmod") == "mapPassageView")
			{
				$this->getMapsPassage();
				return;
			}
				
			if ($this->request->get("actionmod") == "mapPassageSave")
			{
				$this->mapPassageSave();
				return;
			}
				

			if ($this->request->get("actionmod") == "mapDoorsSave")
			{
				$this->mapDoorsSave();
				return;
			}



			if (isset($_FILES['mFile']) )
			{
				$this->uploadImage($_FILES['mFile']);
				$this->currentMap = new Map("rw", "id", $this->map_id);
			}

			if (isset($_FILES['mBackground']) )
			{
				$this->uploadBg($_FILES['mBackground']);
			}

			if ($this->request->get("resetPoint") == "ok")
			{
				$x = round($this->request->get("x"));
				$y = round($this->request->get("y"));
				$this->currentMap->resetFond($x, $y);
				header("location: index.php?action=mapEditor&id={$this->map_id}");
				exit();
			}



			if (trim($this->request->get("activPoint")) || trim($this->request->get("desactivPoint")))
			{
				$this->updateMatrice();
				$this->currentMap = null;
				$this->currentMap = new Map("rw", "id", $this->map_id);

			}

			$arrayYlines = $this->response->doc->createElement("yLines");
			$array1 = explode("\n", $this->currentMap->field->matrice);
			if (is_array($array1) && count($array1))
			foreach ($array1 as $key => $value)
			{
				$array2 = explode("-", $value);
				if (is_array($array2) && count($array2))
				{
					$array1[$key] = $array2;
				} else {
					unset($array1[$key]);
				}
			}


			foreach ($array1 as $key => $value)
			{
				$arrayXlines = $this->response->doc->createElement("xLines");

				foreach ($value as $key2 => $value2)
				{

					$obj = new stdClass();
					$valDoor = "{$key2}_{$key}";
					if (in_array($valDoor, $this->currentMap->getDoorPoints()))
					{
						$obj->val = "[door]";
					} else {
						$obj->val = $value2;
					}

					$xVal = new DOMElement("xVal");

					$MapNode = $this->response->mapObjectXML($obj, "xVal", array("val"=>"val"));
					$arrayXlines->appendChild($MapNode);
				}
				$arrayYlines->appendChild($arrayXlines);
			}

			$this->response->root->appendChild($arrayYlines);




			// read user infos
			$tab = Array(
			"id"  => "mid",
			"name"  => "mname",
			"matrice" => "mmatrice",
			"file" => "mfile"
			);
			$node = $this->currentMap->toXML("map",$tab);
			$this->response->root->appendChild($node);
			header('Pragma:nocache');
			$this->response->setXSLT("views/maps/editor.xsl");

		}

	}

	public function defaultActions(){
		if (!$this->currentMap->isOk())
		{
			header("location: index.php?action=mapList");
			exit();
		}
		$this->response->setXSLT("views/login.xsl");
	}

	private function uploadImage($file)
	{
		//$this->currentMap = new Map("rw", "id", $map->field->id);
		if ($file['type'] == "image/png")
		if ($file['size'] && $file['error'] == 0)
		{
			$ext = "png";
			@unlink( "mapFiles/map_{$this->currentMap->field->id}.{$ext}");
			move_uploaded_file($file['tmp_name'], "mapFiles/map_{$this->currentMap->field->id}.{$ext}");
			$this->currentMap->field->file = "map_{$this->currentMap->field->id}.{$ext}";
			$this->currentMap->resizeImage(800, 600);
			$this->currentMap->resizeImage(240, 180, "mapFiles/mini_{$this->currentMap->field->id}.{$ext}");
			$this->currentMap = null;
		}
	}

	private function uploadBg($file)
	{
		//$this->currentMap = new Map("rw", "id", $map->field->id);
		if ($file['type'] == "image/png")
		if ($file['size'] && $file['error'] == 0)
		{
			$ext = "png";
			@unlink( "mapFiles/bg_{$this->currentMap->field->id}.{$ext}");
			move_uploaded_file($file['tmp_name'], "mapFiles/bg_{$this->currentMap->field->id}.{$ext}");
			/**
			 $this->currentMap->field->file = "map_{$this->currentMap->field->id}.{$ext}";
			 $this->currentMap->resizeImage(800, 600);
			 $this->currentMap->resizeImage(240, 180, "mapFiles/mini_{$this->currentMap->field->id}.{$ext}");
			 $this->currentMap = null;
			 */
		}
	}

	private function updateMatrice()
	{
		$tblMatrice = explode("\n", $this->currentMap->field->matrice);
		if (is_array($tblMatrice) && count($tblMatrice))
		foreach ($tblMatrice as $key => $value)
		{
			$array2 = explode("-", $value);
			if (is_array($array2) && count($array2))
			{
				$tblMatrice[$key] = $array2;
			} else {
				unset($tblMatrice[$key]);
			}
		}


		//echo "<pre>".print_r($tblMatrice, true)."</pre>";
		//echo "<pre>".print_r($this->request->get("activPoint"), true)."</pre>";

		if (trim($this->request->get("activPoint")))
		{
			$tblActiv = explode(";", trim($this->request->get("activPoint")));



			if (count($tblActiv))
			foreach ($tblActiv as $point)
			{
				$point = explode("_", $point);
				if (count($point) == 2 && isset($tblMatrice[$point[1]][$point[0]]))
				{
					//echo "<pre>".print_r($point, true)."</pre>";
					$tblMatrice[$point[1]][$point[0]] = "[1]";
				}

			}
		}

		if (trim($this->request->get("desactivPoint")))
		{
			$tblDesactiv = split(";", trim($this->request->get("desactivPoint")));
			if (count($tblDesactiv))
			foreach ($tblDesactiv as $point)
			{

				$this->mapPassageSave($point, false);
				$point = explode("_", $point);


				if (count($point) == 2 && isset($tblMatrice[$point[1]][$point[0]]))
				{

					$tblMatrice[$point[1]][$point[0]] = "[0]";
				}

			}
		}

		foreach ($tblMatrice as $key => $value)
		{
			$tblMatrice[$key] = implode("-", $value);
		}
		$this->currentMap->field->matrice = implode("\n", $tblMatrice);
	}


	function mapPassageSave($door_info = null, $exit = true)
	{
		if (is_null($door_info)) $door_info = trim($this->request->get("door_info"));
		$door_id = 0;
		$doors = new Doors();
		$result = $doors->getDoorsComplex(" WHERE map_id = {$this->currentMap->field->id} and point = '{$door_info}'", "array");
		if (count($result))
		{
			$door_id = $result[0]->id;
			$doorDel = new Door("rw", "id", $door_id);
			if ($doorDel->isOk())
			{
				$doorDel->delete();
			}
			$doorDel = null;
		}
		if ($exit) exit();
	}

	function mapDoorsSave()
	{
		$doors = new Doors();
		$door_info = trim($this->request->get("door_info"));
		$pointId = round($this->request->get("point_id"));
		$toId = round($this->request->get("toPoint"));

		if ($pointId == 0)
		{
			$doorIn = new Door('c');
			$doorIn->field->map_id = $this->currentMap->field->id;
			$doorIn->field->point = $door_info;
			$doorIn->field->toid = 0;
			$doorIn = null;
		} else {
			$query = "UPDATE `door` set toid = 0 WHERE toid = {$pointId}";
			$this->database->queries($query);

		}
		$result = $doors->getDoorsComplex(" WHERE map_id = {$this->currentMap->field->id} and point = '{$door_info}'", "array");
		if (!count($result))
		{
			exit();

		}
		$door_id = $result[0]->id;
		$doorIn = new Door("rw", "id", $door_id);
		if (!$doorIn->isOk())
		{
			exit();
		}
		$doorIn->field->toid = $toId;

		if ($toId) {
			$doorOut = new Door("rw", "id", $toId);
			if ($doorOut->isOk())
			{
				$doorOut->field->toid = $doorIn->field->id;
				$doorOut = null;
			}
		}
		$doorIn = null;

		exit();

	}

	function getMapsPassage()
	{
		$this->response->setXSLT("views/maps/mapPassage.xsl");

	}

	function getMapsDoors()
	{

		$door_info = trim($this->request->get("door_info"));

		$door_id = 0;
		$doors = new Doors();
		$result = $doors->getDoorsComplex(" WHERE map_id = {$this->currentMap->field->id} and point = '{$door_info}'", "array");
		if (count($result))
		{
			$door_id = $result[0]->id;
		}

		$door = new Door("r", "id", $door_id);

		$toDoorId = 0;
		$toMapId = 0;
		if ($door->isOk())
		{
			$toDoorId = round($door->field->toid);
			$toDoor = new Door("r", "id", $toDoorId);
			if ($toDoor->isOk())
			{
				$toMapId = $toDoor->field->map_id;
			}
		}

		$currDoorXml  = $this->response->doc->createElement("currDoor");
		$currDoorXml->appendChild($this->response->doc->createTextNode($door_id));
		$this->response->add($currDoorXml);

		$toMapXml  = $this->response->doc->createElement("toMap");
		$toMapXml->appendChild($this->response->doc->createTextNode($toMapId));
		$this->response->add($toMapXml);
			
		$toDoorXml  = $this->response->doc->createElement("toDoor");
		$toDoorXml->appendChild($this->response->doc->createTextNode($toDoorId));
		$this->response->add($toDoorXml);
			
			
		$query_where = " WHERE id IN ( SELECT DISTINCT map_id FROM door WHERE ".
						"(map_id = map.id ".
						"and (toid is NULL or toid = 0 or door.id = {$toDoorId}))  ".
						")";
		$maps = new Maps();
		$nodeMaps = $maps->getMapsComplex($query_where);
		$this->response->add($nodeMaps);
			
			
		$this->response->setXSLT("views/maps/mapSelect.xsl");
	}
}